package com.zl.codereview.util;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @author: zhaoxinliang
 * @date: 2021/8/26 9:48
 * @description:
 */
public class ThreadExecutors<T> {

    private final ExecutorService executorService =
        Executors.newCachedThreadPool();

    private final LinkedList<CompletableFuture> futures = new LinkedList<>();

    public CompletableFuture<T> aysnc(Supplier<T> supplier) {
        CompletableFuture<T> completableFuture = CompletableFuture.supplyAsync(supplier, executorService);
        futures.addFirst(completableFuture);
        return completableFuture;
    }

    public CompletableFuture<List<T>> aysncList(Supplier<List<T>> supplier) {
        CompletableFuture<List<T>> completableFuture = CompletableFuture.supplyAsync(supplier, executorService);
        futures.addFirst(completableFuture);
        return completableFuture;
    }

    public void hasException() {
        CompletableFuture[] completableFutures = new CompletableFuture[futures.size()];
        CompletableFuture[] futures = this.futures.toArray(completableFutures);
        CompletableFuture.allOf(futures).exceptionally(throwable -> {
            throw new RuntimeException(throwable.getMessage());
        });
    }

    public Object get(CompletableFuture completableFuture)  {
        Object object = null;
        try {
            object = completableFuture.get(30, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

}
